package com.flyco.modules.oms.handle.impl;

import com.flyco.common.constant.StockConstant;
import com.flyco.common.util.IdUtil;
import com.flyco.common.util.RedisUtil;
import com.flyco.modules.oms.entity.OmsElemeGoodsItem;
import com.flyco.modules.oms.entity.OmsJddjOrderProduct;
import com.flyco.modules.oms.entity.OmsOrderInvoice;
import com.flyco.modules.oms.entity.OmsOrderItem;
import com.flyco.modules.oms.handle.IThirdOrderHandle;
import com.flyco.modules.oms.vo.OmsElemeRetailOrderPage;
import com.flyco.modules.oms.vo.OmsJddjOrderPage;
import com.flyco.modules.oms.vo.OmsOrderPage;
import com.flyco.modules.pms.service.IPmsProductService;
import com.flyco.modules.pms.vo.PmsProductSkuForOrderVO;
import com.flyco.modules.stm.vo.StmStockVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ThirdOrderHandleImpl implements IThirdOrderHandle {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IPmsProductService pmsProductService;

    @Override
    public OmsOrderPage generateStoreOrderWithEleme(OmsElemeRetailOrderPage page, Long storeId) {
        OmsOrderPage order = new OmsOrderPage();
        order.setId(page.getId());
        order.setStoreId(storeId);
        order.setOrderSn(page.getId());
        order.setMemberId(1L);
        order.setCreateTime(page.getCreatedAt());
        order.setTotalAmount(page.getOriginalPrice());
        order.setPayAmount(page.getTotalPrice());
        order.setEffectiveAmount(page.getIncome());
        //order.setDiscountAmount(page.getServiceFee());
        order.setPayType("unionPay");
        order.setSourceType("admin");
        order.setSourceSystem("third");
        order.setStatus(3);
        order.setProductStatus(5);
        order.setPayStatus(4);
        order.setReceiverName("饿了么默认用户");
        order.setReceiverPhone("10000000000");
        order.setConfirmStatus(1);
        List<OmsOrderItem> omsOrderItemList = new ArrayList<>();
        List<OmsOrderInvoice> omsOrderInvoiceList = new ArrayList<>();
        OmsOrderInvoice orderInvoice = new OmsOrderInvoice();
        orderInvoice.setOrderId(page.getId());
        orderInvoice.setInvoiceType("0");
        orderInvoice.setInvoiceTitle("个人");
        omsOrderInvoiceList.add(orderInvoice);
        order.setOmsOrderInvoiceList(omsOrderInvoiceList);
        List<String> barCodes = page.getOmsElemeGoodsItemList().stream().map(r-> r.getBarCode()).collect(Collectors.toList());
        List<PmsProductSkuForOrderVO> skuForOrderVOS = pmsProductService.getProductSkuForOrderList(storeId, barCodes);
        Map<String, PmsProductSkuForOrderVO> skuCodeMap = skuForOrderVOS.stream().collect(Collectors.toMap(PmsProductSkuForOrderVO::getSkuCode, t -> t));

        for (OmsElemeGoodsItem item : page.getOmsElemeGoodsItemList()) {
            OmsOrderItem orderItem = new OmsOrderItem();
            orderItem.setOrderId(page.getId());
            orderItem.setOrderSn(page.getId());
            orderItem.setProductSkuCode(item.getBarCode());
            //
            orderItem.setProductQuantity(item.getQty());
            if (item.getPreferentialQty() >0) {
                orderItem.setProductPrice(item.getAfterPreferentialPrice());
            } else {
                orderItem.setProductPrice(item.getBeforePreferentialPrice());
            }
            orderItem.setTotalPromotionAmount(new BigDecimal(isNumeric(item.getShopPart())? item.getShopPart() : "0" ));
            orderItem.setTotalCouponAmount(new BigDecimal(isNumeric(item.getShopCouponAmount()) ? item.getShopCouponAmount() : "0" ));
            orderItem.setTotalRealAmount(new BigDecimal(isNumeric(item.getShopRedbagAmount()) ? item.getShopRedbagAmount() : "0" ));
            orderItem.setTotalIntegrationAmount(new BigDecimal(isNumeric(item.getShopCashAmount()) ? item.getShopCashAmount() : "0" ));
            orderItem.setProductName(item.getProductName());
            if (skuCodeMap.containsKey(item.getBarCode())) {
                PmsProductSkuForOrderVO vo = skuCodeMap.get(item.getBarCode());
                orderItem.setProductId(vo.getId());
                orderItem.setProductPic(vo.getPic());
                orderItem.setProductBrand(vo.getBrandName());
                orderItem.setProductSn(vo.getProductSn());
                orderItem.setProductSkuId(vo.getSkuId());
                orderItem.setProductCategoryId(vo.getProductCategoryId());
            }
            omsOrderItemList.add(orderItem);
        }
        order.setOmsOrderItemList(omsOrderItemList);
        return order;
    }

    @Override
    public OmsOrderPage generateStoreOrderWithJddj(OmsJddjOrderPage page, Long storeId) {
        OmsOrderPage order = new OmsOrderPage();
        order.setId(page.getId());
        order.setStoreId(storeId);
        order.setOrderSn(page.getId());
        order.setMemberId(1L);
        order.setCreateTime(page.getOrderStartTime());
        order.setPaymentTime(page.getOrderPurchaseTime());
        order.setTotalAmount(long2BigDecimal(page.getOrderTotalMoney()));
        order.setPayAmount(long2BigDecimal(page.getOrderBuyerPayableMoney()));
        order.setEffectiveAmount(long2BigDecimal(page.getOrderBuyerPayableMoney()));
        order.setFreightAmount(long2BigDecimal(page.getOrderReceivableFreight()));
        order.setPromotionAmount(long2BigDecimal(page.getOrderDiscountMoney()));
        order.setIntegrationAmount(long2BigDecimal(page.getPlatformPointsDeductionMoney()));
        order.setPayType("unionPay");
        order.setSourceType("admin");
        order.setSourceSystem("third");
        order.setStatus(3);
        order.setProductStatus(5);
        order.setPayStatus(4);
        order.setReceiverName("京东到家默认用户");
        order.setReceiverPhone("10000000000");
        order.setConfirmStatus(1);
        List<OmsOrderItem> omsOrderItemList = new ArrayList<>();
        List<OmsOrderInvoice> omsOrderInvoiceList = new ArrayList<>();
        OmsOrderInvoice orderInvoice = new OmsOrderInvoice();
        orderInvoice.setOrderId(page.getId());
        orderInvoice.setInvoiceType("0");
        orderInvoice.setInvoiceTitle("个人");
        omsOrderInvoiceList.add(orderInvoice);
        order.setOmsOrderInvoiceList(omsOrderInvoiceList);
        List<String> barCodes = page.getOmsJddjOrderProductList().stream().map(r->r.getUpcCode()).collect(Collectors.toList());
        List<PmsProductSkuForOrderVO> skuForOrderVOS = pmsProductService.getProductSkuForOrderList(storeId, barCodes);
        Map<String, PmsProductSkuForOrderVO> skuCodeMap = skuForOrderVOS.stream().collect(Collectors.toMap(PmsProductSkuForOrderVO::getSkuCode, t -> t));
        for (OmsJddjOrderProduct item : page.getOmsJddjOrderProductList()) {
            OmsOrderItem orderItem = new OmsOrderItem();
            orderItem.setOrderId(page.getId());
            orderItem.setOrderSn(page.getId());
            orderItem.setProductSkuCode(item.getUpcCode());
            orderItem.setProductName(item.getSkuName());
            orderItem.setProductPrice(long2BigDecimal(item.getSkuJdPrice()));
            orderItem.setProductQuantity(item.getSkuCount());
            if (skuCodeMap.containsKey(item.getUpcCode())) {
                PmsProductSkuForOrderVO vo = skuCodeMap.get(item.getUpcCode());
                orderItem.setProductId(vo.getId());
                orderItem.setProductPic(vo.getPic());
                orderItem.setProductBrand(vo.getBrandName());
                orderItem.setProductSn(vo.getProductSn());
                orderItem.setProductSkuId(vo.getSkuId());
                orderItem.setProductCategoryId(vo.getProductCategoryId());
            }
            omsOrderItemList.add(orderItem);
        }
        order.setOmsOrderItemList(omsOrderItemList);
        return order;
    }


    @Override
    public List<StmStockVO> generateStockRecord(OmsOrderPage orderPage) {
        List<StmStockVO> outStockVOList = new ArrayList<>();
        orderPage.getOmsOrderItemList().forEach(item->{
            StmStockVO vo = BeanUtils.instantiateClass(StmStockVO.class);
            vo.setProductId(item.getProductId());
            vo.setProductSn(item.getProductSn());
            vo.setStockType(StockConstant.STOCK_TYPE_GOODS);
            vo.setProductQty(item.getProductQuantity());
            outStockVOList.add(vo);
        });
        return outStockVOList;
    }

    public static boolean isNumeric(String str) {
        return str.matches("-?[0-9]+.？[0-9]*");
    }

    public static BigDecimal long2BigDecimal(Long num) {
        return new BigDecimal(num).divide(new BigDecimal(100));
    }

    /**
     * 生成18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id
     */
    @Override
    public String generateOrderSn() {
        String date = new SimpleDateFormat("yyyyMMddHH").format(new Date());
        String key = "portal:orderId:" + date;
        long seq = redisUtil.incr(key, 1);
        if (seq == 1L) {
            seq = redisUtil.incr(key, (long) (Math.random() * 500000));
            redisUtil.expire(key, 3600 * 2L);
        }
        return "" + IdUtil.genId("yyMMddHH{s}{s}{s}{s}{s}{r}{s}7", seq, 6);
    }
}
